using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace RESTfulCore
{
    public class RestRouteFluentInterface
    {
        private readonly RestRoute _restRoute;

        public RestRouteFluentInterface(RestRoute restRoute)
        {
            _restRoute = restRoute;
        }

        public RestRouteFluentInterface Route(string route)
        {
            _restRoute.ActionToInvoke = route.Substring(0, route.IndexOf('/'));
            _restRoute.OriginalRoute = route;
            _restRoute.RequestRoute = route;

            return this;
        }

        public RestRouteFluentInterface SetParameter(string key, dynamic value)
        {
            if (_restRoute.RouteDictionary == null)
                _restRoute.RouteDictionary = new Dictionary<string, dynamic>();

            _restRoute.RouteDictionary.Add(new KeyValuePair<string, dynamic>(key, value));

            return this;
        }

        public RestRouteFluentInterface BuildRoute()
        {
            var routeBuilder = new StringBuilder();

            routeBuilder.Append(_restRoute.RequestRoute);

            //TODO: needs to do a replace for request route so that we can have add param segments in any order
            //foreach (KeyValuePair<string, string> kvp in instance.RouteDictionary)
            Parallel.ForEach(_restRoute.RouteDictionary, r =>
            {
                routeBuilder.Replace($"{{{r.Key}}}", r.Value as string);
            });

            _restRoute.RequestRoute = routeBuilder.ToString();

            return this;
        }
    }
}